import styled from "styled-components";
import { BrowserRouter, Route, Routes, useNavigate } from "react-router-dom";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Space, Spin, Input, Card, message } from "antd";
import React, { useState, useEffect } from "react";
import { login } from "../../services/user";
import { loginByExtension, hasExtension } from "../../services/polkadot-extension-handle";
import store from "../../utils/store";
import { loading, alert, confirm, notiError, notiOK, alertError } from "../../utils/antd-helper";
import * as oss from "../../services/oss";
import { newAuthCode, updateAccount, applyInviteCode, initiateAuth } from "../../services/graphql";
import { InitAPI, Common, defaultConfig } from "cess-js-sdk-frontend";
import { getMappingAccount, signAndSendEvm, signMessage } from 'evm-account-mapping-sdk'
import { custom, createWalletClient, hashMessage } from 'viem'
import { mainnet } from 'viem/chains'
import { useAccount, useWalletClient, useFeeData, erc20ABI, useContractWrite, useBalance } from 'wagmi'
const { stringToU8a } = require("@polkadot/util");


let lock = false;

let sdk = null;
let walletClient;
let mappingAccount;

const App = ({ className }) => {

    const [msg, setMsg] = useState("");
    const [hashStr, setHashStr] = useState("");
    const [u8arr, setU8arr] = useState();
    const [result, setResult] = useState("");
    const [invitecode, setInvitecode] = useState("");

    const sleep = s => {
        return new Promise((resolve, reject) => {
            setTimeout(function () {
                resolve();
            }, s * 1000);
        });
    };

    useEffect(() => {
        init();
        let u = window.location.href;
        if (u.includes("/login?from=")) {
            let t = u.split("/login?from=")[1];
            if (t) {
                setInvitecode(t);
            }
        }
    }, []);
    const init = async () => {
        // setConnectStatus('connecting...');
        try {
            const { api, keyring } = await InitAPI(defaultConfig);
            window.api = api;
            window.keyring = keyring;
            // setConnectStatus('connect success');
            // console.log("rpc connect success");
            return { api, keyring };
        } catch (e) {
            // setConnectStatus(e.message);
            console.log('has error');
            console.log(e);
        }
    };
    const onSign = async () => {
        try {
            if (lock) return;
            lock = true;
            loading('loading...');
            while (!window.api || !window.keyring) {
                await sleep(0.5);
            }
            let randomStr = msg;
            if (!randomStr) {
                return alertError('message is required');
            }
            walletClient = createWalletClient({ chain: mainnet, transport: custom(window.ethereum) });
            const [address] = await walletClient.requestAddresses();
            console.log({ address, road: 'there' })
            const SS58Prefix = (window.api?.consts?.system?.ss58Prefix || 11330).toNumber();
            let ma = await getMappingAccount(window.api, walletClient, { address }, { SS58Prefix });
            if (!ma) {
                return;
            }
            mappingAccount = ma;
            let acc = ma;
            acc.address = ma.substrateAddress;
            store.set("addr", acc.address);
            store.set("account", acc);

            console.log({ randomStr });
            console.log(ma.evmAddress);
            // if (!randomStr.includes("<Bytes>")) {
            // 	randomStr = `<Bytes>${randomStr}</Bytes>`;
            // }
            // randomStr='hello';
            // randomStr=randomStr.slice(0,32);
            let sign = await signMessage(walletClient, { address: ma.evmAddress }, randomStr);
            // sign = sign.replace("0x", "");
            // console.log('sign=====================', sign);
            setResult(sign);
        } catch (e) {
            console.log(e);
        } finally {
            lock = false;
            loading();
        }
    }
    const onInput = e => {
        let v = e.target.value;
        setMsg(v);
        // const hash = hashMessage(e.target.value,'keccak_256');
        let u8 = stringToU8a(v);
        setU8arr(u8);
        const hash = hashMessage({ raw: u8 });
        setHashStr(hash);
    };
    return (
        <div className={className}>
            <div>
                <h4>Sign message tool</h4>
                <Input placeholder="Original Message String" onChange={onInput} /><br /><br />
                <Button type="primary" onClick={onSign}>Sign</Button><br /><br />
                <Input placeholder="Result" value={result} /><br /><br />
                <Input placeholder="Message Hash" value={hashStr} /><br /><br />
                <Input placeholder="Uint8Array" value={u8arr} /><br /><br />
            </div>
        </div>
    );
};
export default styled(App)`
	padding:30px;
`;
